package com.doraz.orb.methods.file;

import java.io.InputStream;

import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.doraz.orb.Constants;
import com.doraz.orb.methods.OrbMethod;
import com.doraz.orb.structs.OrbObject;
import com.doraz.orb.structs.SearchResult;
import com.doraz.orb.utils.IntValidator;
import com.doraz.orb.utils.XMLUtils;

public class Browse extends OrbMethod {
	private final static String TAG = "file.browse";
	
	public Browse() {
		super("file.browse", "xml/file.browse", Constants.RETURN_XML);
		addParam("path", Constants.MYCOMPUTER);
		addParam("flags", ""+7);
		addParam("fields", Constants.FIELDS);
	}
	
	public Browse(String path, String extensionFilter) {
		super("file.browse",  "xml/file.browse", Constants.RETURN_XML);
		addParam("path", path);
		addParam("flags", ""+7);
		addParam("fields", Constants.FIELDS);
		if(extensionFilter != null) {
			addParam("extensionFilter", extensionFilter);
		}
	}
	
	@Override
	public OrbObject parseResponse(InputStream in) {
		SearchResult result = null;
		Document doc = XMLUtils.getDocument(in);
		Element status = (Element) (doc.getElementsByTagName("status"));
		if(status != null && new IntValidator(-1).parseInt(status.getAttribute("code")) != 0) {
			//Error Occurred
			Log.w(TAG, "Errors occurred: "+status.getAttribute("desc"));
		}
		
		NodeList rList = doc.getElementsByTagName("searchResult");
		if(rList.getLength() > 0) {
			Element results = (Element) rList.item(0);
			result = XMLUtils.parseResult(results);
		}
		
		return result;
	}

}
